import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";

import React from "react";

import { addon, Ref, log, getObject } from "pao-aop";
import { IProductSignService, ProductSign } from "src/models/productSign";
import { IProductTypeService, ProductType } from "src/models/productType";
import { AnalysisSign } from "src/models/baseSign";
import { User } from "src/business/models/user";
import { ProductClassify, IProductClassifyService, ProductClassifyCondition, ParentCustomAttribute } from "src/models/productClassify";
import { PRODUCT_SIGN_ID, isPermission, UPLOAD_URL, beforeUpload, ROUTE_PATH } from "../../app/util-tool";
import { IndustryInternetSignAppStorage } from "../../app/appStorage";
import { ICompanyTemplateSignService } from "src/models/companySign";
import { message, Modal, Button } from "antd";
import { PermissionList } from "../../app/permission";
import FormCreator, { InputType } from "src/business/components/form-creator";
import { GetFieldDecoratorOptions, FormProps } from "antd/lib/form/Form";
import { FormItemProps } from "antd/lib/form";
import NTDivStyle from "src/business/style-components/div-style";
import { NTOperationTable } from "src/business/components/operation-table";
import { NTModal } from "src/projects/industryInternetSign/components/modal";
import { SignPreview } from "src/projects/industryInternetSign/components/sign-preview";
import { DataObject } from "src/business/components/button-alert";
/** 获取表单props属性 */
let formProps: any;
/**
 * 组件：更改产品标识视图状态
 */
export interface ChangeProductSignViewState extends ReactViewState {
    /** 产品标识数据源 */
    data: ProductSign;
    /** 产品类型数据集合 */
    product_data?: ProductType[];
    // /** 企业标识信息对象 */
    // company_sign?: CompanySign;
    /** modal显示判断 */
    visible: boolean;
    /** 二维码显示判断 */
    showCode: boolean;
    src?: string;
    /** 解析标识 */
    analysSin: AnalysisSign;
    /** 用于提交的对象 */
    submit_data?: ProductSign;
    /** 用户信息 */
    user_data?: User;
    /** 标识输入框是否可编辑 */
    check_code: boolean;
    /** 标识码显示前缀 */
    before_handle_code?: string;
    /** 滚动条 */
    loading?: boolean;
    /** 产品分类modal显示判断 */
    product_classify_visible?: boolean;
    /** 产品分类列表数据源 */
    data_source?: ProductClassify[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 选中产品分类对象 */
    product_classify?: ProductClassify;
    /** 企业标识编码 */
    company_handle_code?: string;
    /** 企业标识名称 */
    company_handle_name?: string;
    /** 产品标识是否置顶单选框数值 */
    // productSignRadioGroupValue?: boolean;
}

/**
 * 组件：更改产品标识视图
 * 控制更改产品标识视图
 */
export class ChangeProductSignView extends ReactView<ChangeProductSignViewControl, ChangeProductSignViewState> {
    private columns_data_source = [{
        title: '产品分类名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    constructor(props: any) {
        super(props);
        this.state = {
            data: {},
            product_data: [],
            // company_sign: {},
            visible: false,
            showCode: false,
            src: '',
            analysSin: {},
            check_code: false,
            before_handle_code: '',
            loading: false,
            // productSignRadioGroupValue: true,
        };
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.setState({
            loading: true
        });
        let { [PRODUCT_SIGN_ID]: id } = this.props.match!.params;

        this.querySelectList()
            .catch(error => {
                log("SelectList", error.message);
            });

        let condition: ProductClassifyCondition = {};
        this.queryList(condition, 1, 10)
            .then(() => { })
            .catch(error => {
                log("productClassifyViewControl", error.message);
            });
        if (id) {
            this.queryData(id)
                .then(() => {
                    this.setState({
                        loading: false
                    });
                })
                .catch(error => {
                    this.setState({
                        loading: false
                    });
                    log("ChangeProductSignViewControl", error.message);
                });
        } else {
            // let company_sign = IndustryInternetSignAppStorage.getCurrentCompanySign();
            this.setState({
                // company_sign: company_sign ? company_sign : {},
                check_code: false,
                loading: false
            });
        }
    }
    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList({}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("ChangeProductSignViewControl-pageOnCick", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList({}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("ChangeProductSignViewControl-showSizeChange", error.message);
            });
    }
    // 查询产品分类列表信息
    async queryList(condition: ProductClassifyCondition, page: number, count: number) {
        const data = await this.productClassifyService!()!.get_product_classify_list!(condition, page, count)!;
        this.setState({
            total_data: data ? data!.total : 0, // 应当取接口返回的总数
            data_source: data ? data!.result : []
        });
    }

    // 初始化模版服务
    productClassifyService?() {
        return getObject(this.props.productClassifyService_Fac!);
    }
    /**
     * 引用模版按钮方法
     */
    select_parent = () => {
        this.setState({
            // stencil_value: [],
            product_classify_visible: true
        });
    }

    /** 模版选择框确定回调方法 */
    handleOk = (e: any) => {
        // 把已经选中的自定义属性列表放入data中
        let data = this.state.data;
        let product_classify = this.state.product_classify;
        // 如果有选中分类，用分类Id去查询接口，返回所有的自定义类目信息，如有企业信息，则把企业信息记录起来
        if (product_classify) {
            this.productClassifyService!()!.get_custom_attribute_list!(product_classify.id!)!
                .then((parentCoustomAttribute: ParentCustomAttribute) => {
                    console.log('最终值', parentCoustomAttribute.custom_attribute);
                    data!.custom_attribute = parentCoustomAttribute.custom_attribute;
                    data.parent_id = product_classify!.id;
                    if (data.company_handle_code && data.company_handle_name) {
                        this.setState({
                            company_handle_code: data.company_handle_code,
                            company_handle_name: data.company_handle_name,
                            product_classify_visible: false,
                            data
                        });
                    } else {
                        this.setState({
                            product_classify_visible: false,
                            data
                        });
                    }
                    // 设置自定义控件的值
                    formProps.setFieldsValue({
                        custom_attribute: data!.custom_attribute,
                        parent_id: data.parent_id
                    });
                })
                .catch(error => {
                    log("productClassifyViewControl", error.message);
                });
        }
        this.setState({
            product_classify_visible: false
        });

    }

    /** 模版选择框取消回调方法 */
    handleCancel = (e: any) => {
        this.setState({
            product_classify_visible: false,
        });
    }
    /** 行选中回调 */
    private handleRowSelect = (e: ProductClassify[]) => {
        let product_classify;
        if (e.length > 0) {
            for (let i = 0; i < e.length; i++) {
                product_classify = e[i];
            }
        }
        this.setState({
            product_classify: product_classify,
        });
    }

    /**
     * 初始化产品标识服务
     */
    productSignServices?() {
        return getObject(this.props.productSignService_Fac!);
    }

    /**
     * 初始化产品类型服务
     */
    productTypeService?() {
        return getObject(this.props.productTypeService_Fac!);
    }

    /**
     * 初始化企业服务
     */
    companyTemplateSignService?() {
        return getObject(this.props.companyTemplateSignService_fac!);
    }

    /**
     * 查询产品标识详情信息
     */
    async queryData(id: string) {
        const data = await this.productSignServices!()!.get_product!(id)!;
        this.setState({
            data: data!,
            check_code: true,
            before_handle_code: data ? data!.handle_code!.slice(0, data!.handle_code!.indexOf('@') + 1) : this.state.before_handle_code,
            // productSignRadioGroupValue: data && data!.module_sort && data!.module_sort!.product && data!.module_sort!.product!.show_sort && data!.module_sort!.product!.show_sort === 1 ? true : this.state.productSignRadioGroupValue,
        });
    }

    /**
     * 查询产品类别信息
     */
    async querySelectList() {
        const product_data = await this.productTypeService!()!.get_product_type_list!()!;
        let user_data = IndustryInternetSignAppStorage.getCurrentUser();
        this.setState({
            product_data: product_data!.result,
            // company_sign: company_sign ? company_sign : {},
            user_data: user_data[0], // 以后梦晴改成对象后，把0去掉
            before_handle_code: (user_data[0] ? user_data[0].account : "") + '/cpbs@',
        });
    }

    /**
     * 生成二维码图片，返回url地址
     */
    async generateIdentifierQRCode(code: string, data: ProductSign) {
        const src = await this.companyTemplateSignService!()!.get_qr_code!(code)!;
        this.setState({ src: '/' + src.url });
        data!.rc_code = '/' + src.url;
        let { [PRODUCT_SIGN_ID]: id } = this.props.match!.params;
        if (id) {
            data.id = id;
        }
        let result = await this.productSignServices!()!.insert!(data)!;
        if (result) {
            this.setState({
                showCode: true
            });
            message.info('保存成功');
        } else {
            message.info('保存失败');
        }
    }

    /** 提交并生成二维码方法 */
    save_build_qrCode = () => {
        this.setState({
            loading: true
        });
        let data = this.state.submit_data;
        this.generateIdentifierQRCode(data!.handle_code!, data!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({ loading: false });
                log("productSignViewControl", error.message);
                message.info("保存失败" + error.message);
            });

    }
    /** 提交按钮 */
    onClickSubmit = (e: any, data: ProductSign) => {
        data!.handle_code = (this.state.before_handle_code ? this.state.before_handle_code : "") + data!.handle_code;
        data!.company_handle_name = this.state.company_handle_name ? this.state.company_handle_name : '';
        data!.company_handle_code = this.state.company_handle_code ? this.state.company_handle_code : '';
        this.insertPreview(data!)
            .catch(error => {
                log("insert_preview", error.message);
            });
    }
    /** 新增排序服务调用 */
    async insertPreview(data: ProductSign) {
        // let module_sort: ModuleSort = {};
        // module_sort.company = {
        //     is_show: true,
        //     show_sort: this.state.companyRadioGroupValue// data.company_show_sort
        // };
        // module_sort.product = {
        //     is_show: true,
        //     show_sort: this.state.categoryRadioGroupValue// data.category_show_sort
        // };
        // data.company_is_show = undefined;
        // data.company_show_sort = undefined;
        // data.category_is_show = undefined;
        // data.category_show_sort = undefined;
        let result = await this.productSignServices!()!.insert_preview!(data)!;
        // data!.company_handle_name = undefined;
        // data!.company_handle_code = undefined;
        // result.module_sort = module_sort;
        // data.module_sort = module_sort;
        this.setState({
            visible: !this.state.visible,
            submit_data: data,
            analysSin: result
        });
    }
    // /** 企业标识选择框回调 */
    // onClickCompany = (e: any) => {
    //     let company_sign = this.state.company_sign;
    //     company_sign!.handle_code = e.key;
    //     this.setState({
    //         company_sign: company_sign
    //     });
    // }

    // /**
    //  * 品类复选按钮方法
    //  */
    // onChangeCategoryRadioGroup = (e: any) => {
    //     this.setState({
    //         categoryRadioGroupValue: e.target.value
    //     });
    // }
    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.ProductSign_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        let { data, product_data, before_handle_code } = this.state;

        /** 产品类型select框 */
        let selectOption: any[] = [];
        if (product_data) {
            product_data!.map((item, idx) => {
                selectOption.push({ id: item.id + '', value: item.product_type_name });
            });
        }

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
        };
        const content = (
            <div>
                <img style={{ width: '850px' }} src={require('../../img/cp_picture.jpg')} />
            </div>
        );
        // const optionRadioGroup = [{ label: '第一', value: 1 }, { label: '第二', value: 2 }];
        // 品类排序复选框
        // const categoryRadioGroup = (
        //     <div>展示排序：
        //         <RadioGroup options={optionRadioGroup} onChange={this.onChangeCategoryRadioGroup} value={this.state.categoryRadioGroupValue} />
        //     </div>
        // );
        let button_alert_data: DataObject[] = [];
        let source = this.state.data_source;
        if (source) {
            for (let i = 0; i < source!.length; i++) {
                button_alert_data.push({ id: source[i].id, name: source[i].handle_name });
            }
        }

        let edit_props = {
            loading: this.state.loading,
            form_items_props: [
                {
                    title: "引用产品分类",
                    need_card: true,
                    // extra: companyRadioGroup,
                    input_props: [
                        {
                            type: InputType.button_alert,
                            label: "产品分类",
                            decorator_id: "parent_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择产品分类" }],
                                initialValue: data.parent_id ? data.parent_id : 'd6fc6564-5b66-11e9-ad52-0c9d92c0dbeb',
                            } as GetFieldDecoratorOptions,
                            option: {
                                button_name: '选择分类',
                                onClick: this.select_parent,
                                alert_type: "success",
                                data: button_alert_data
                            }
                        }
                    ]
                },
                {
                    title: "产品标识信息",
                    need_card: true,
                    // extra: categoryRadioGroup,
                    input_props: [
                        {
                            type: InputType.upload,
                            label: "产品图片",
                            decorator_id: "category_picture",
                            field_decorator_option: {
                                // rules: [{ required: true, message: "请输入正文内容" }],
                                initialValue: data["category_picture"],
                            } as GetFieldDecoratorOptions,
                            form_item_props: {
                                extra: "（请上传大小为1M以内的图片）（可选）"
                            } as FormItemProps,
                            option: {
                                action: UPLOAD_URL,
                                upload_amount: 5,
                                beforeUpload: beforeUpload
                            }
                        },
                        {
                            type: InputType.select,
                            label: "产品类型",
                            decorator_id: "product_type",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择产品类型" }],
                                initialValue: data["product_type"],
                            } as GetFieldDecoratorOptions,
                            option: {
                                data: selectOption,
                                placeholder: "请选择产品类型"
                            }
                        },
                        {
                            type: InputType.input,
                            label: "产品标识名称",
                            decorator_id: "handle_name",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入产品标识名称" }],
                                initialValue: data["handle_name"],
                            } as GetFieldDecoratorOptions,
                            // form_item_props: {
                            //     help: "（必须按照此规则：企业名称首字母大写）"
                            // } as FormItemProps,
                            option: {
                                placeholder: "请输入品类标识名称"
                            }
                        },
                        {
                            type: InputType.input,
                            label: "产品标识",
                            decorator_id: "handle_code",
                            // form_item_props: {
                            //     help: "（必须按照此规则：企业名称首字母大写）"
                            // } as FormItemProps,
                            field_decorator_option: {
                                // rules: [{ validator: checkCode }],
                                rules: [{ required: true, message: "请输入产品标识" }],
                                initialValue: data && data!.handle_code ? data!.handle_code!.slice(data!.handle_code!.indexOf('@') + 1) : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                addonBefore: before_handle_code ? before_handle_code : "",
                                placeholder: "请输入产品标识",
                                disabled: this.state.check_code
                            }
                        },
                        {
                            one_row_inputs: {
                                title: "自定义类目属性",
                                border: true,
                                inputs_props: [
                                    {
                                        type: InputType.customProperties,
                                        col_span: 14,
                                        decorator_id: "custom_attribute",
                                        field_decorator_option: {
                                            // rules: [{ required: true, message: "请输入正文内容" }],
                                            initialValue: data!.custom_attribute,
                                        } as GetFieldDecoratorOptions,
                                        layout: {
                                            labelCol: {
                                                xs: { span: 24 },
                                                sm: { span: 24 },
                                            },
                                            wrapperCol: {
                                                xs: { span: 24 },
                                                sm: { span: 24 },
                                            },
                                        },
                                        option: {
                                            befor_placeholder: '类目名称',
                                            after_placeholder: '请输入类目信息',
                                            type_key: 'format',
                                            before_key: 'label',
                                            after_key: 'value',
                                            // value: data!.custom_attribute,
                                            upload_action: UPLOAD_URL,
                                            upload_amount: 5,
                                            beforeUpload: beforeUpload
                                        }
                                    },
                                    {
                                        type: InputType.popover,
                                        col_span: 10,
                                        layout: {
                                            labelCol: {
                                                xs: { span: 24 },
                                                sm: { span: 4 },
                                            },
                                            wrapperCol: {
                                                xs: { span: 24 },
                                                sm: { span: 20 },
                                            },
                                        },
                                        label: "参考图片",
                                        // decorator_id: undefined,
                                        // default_value: "11",
                                        option: {
                                            title: '详细图片',
                                            content: content,
                                            buttonName: '点击查看',
                                            placement: 'bottom'
                                        }
                                    },
                                ]
                            }
                        }
                    ]
                }
            ],
            form_item_layout: formItemLayout,
            form_props: {
                hideRequiredMark: true
            } as FormProps,
            row_btn_props: {
                style: {
                    justifyContent: " center"
                }
            },
            other_btn_propps: [
                {
                    text: "返回",
                    cb: () => {
                        console.log("返回回调");
                        this.props.history!.push(ROUTE_PATH.productSign);
                    }
                }
            ],
            submit_btn_propps: {
                text: "预览",
                cb: this.onClickSubmit
            }
        };

        return (
            (
                <NTDivStyle.NTDefaultDiv>
                    <Modal
                        title="请选择产品分类！"
                        visible={this.state.product_classify_visible}
                        onOk={() => this.handleOk(formProps)}
                        onCancel={this.handleCancel}
                        closable={false}
                    >
                        <NTOperationTable
                            data_source={this.state.data_source}
                            columns_data_source={this.columns_data_source}
                            on_row_selection={this.handleRowSelect}
                            table_size='middle'
                            type='radio'
                            showHeader={true}
                            bordered={true}
                            total={this.state.total_data}
                            default_page_size={10}
                            total_pages={Math.ceil((this.state.total_data! ? this.state.total_data! : 0) / 10)}
                            show_footer={true}
                            page_on_click={this.pageOnCick}
                            show_size_change={this.showSizeChange}
                        />
                    </Modal>
                    <FormCreator {...edit_props} ref={(e: any) => formProps = e} />
                    {this.state.visible ? <NTModal
                        visible={this.state.visible}
                        closable={false}
                        title="预览"
                        cancelText="返回"
                        okText={"提交并生成二维码"}
                        onCancel={() => { this.setState({ visible: false, showCode: false }); }}
                        onOk={() => { this.setState({ showCode: true, }); }}
                        content={<SignPreview showCode={!this.state.showCode} data={this.state.analysSin} qr_code={this.state.src} />}
                        footer={[
                            // 定义右下角 按钮的地方 可根据需要使用 一个或者 2个按钮
                            !this.state.showCode ?
                                <Button key="back" onClick={() => { this.setState({ visible: false, showCode: false }); }}>返回</Button>
                                :
                                <div />,
                            !this.state.showCode ?
                                <Button key="submit" type="primary" onClick={this.save_build_qrCode}>提交并生成二维码</Button>
                                :
                                <Button
                                    key="back"
                                    onClick={() => {
                                        this.setState(
                                            {
                                                visible: false,
                                                showCode: false
                                            },
                                            () => { this.props.history!.push(ROUTE_PATH.categoryTemplate); }
                                        );
                                    }
                                    }
                                > 返回
                                </Button>,
                        ]
                        }
                    /> : ''}
                </NTDivStyle.NTDefaultDiv>
            )
        );
    }
}

/**
 * 控件：更改产品标识视图
 * 控制更改产品标识视图
 */
@addon('ChangeProductView', '更改产品标识视图', '控制更改产品标识视图')
@reactControl(ChangeProductSignView, true)
export class ChangeProductSignViewControl extends ReactViewControl {

    /**
     * 产品标识服务
     */
    public productSignService_Fac?: Ref<IProductSignService>;

    /** 
     * 产品类型服务
     */
    public productTypeService_Fac?: Ref<IProductTypeService>;
    /**
     * 产品分类服务
     */
    public productClassifyService_Fac?: Ref<IProductClassifyService>;
    /**
     * 企业服务
     */
    public companyTemplateSignService_fac?: Ref<ICompanyTemplateSignService>;
}